#include "main.h"
#include "global.h"


int read_data(char *myFile){
  FILE *file;
  int i;

  file = fopen(myFile,"r");
  if (!file){
    perror("file");
    return -1;
  }
  fread(&count, sizeof(int), 1, file);
  myData=(struct net3D*)realloc (myData, (count+1) * sizeof(net3D));
  fread(&myData, sizeof(net3D), 1, file);
  fclose(file);
  return 0;
}

int save_data(){
  FILE *file;
  int i;

  file = fopen("/home/alex/data.nepovito","w");
  if (!file){
    perror("file");
    return -1;
  }

  //Ecriture de l'entête du fichier
  fwrite(&count,sizeof(int),1,file);
  fwrite(&myData,sizeof(net3D),1,file);
  fclose(file);
  return 0;
}

int ifPresent(int myX,int myY, int myZ){
	int i;
	for (i=0;i<count;i++){
		if (x[i] == myX && y[i] == myY && z[i] == myZ){
			return i;
		}
	}
	return 0;
}

int ifPresentMyData(int myX, int myY, int myZ){
  int i;
  for (i=0;i<count;i++){
    if(myData[i].dec_ipv4 == myX && myData[i].src_port == myY && myData[i].dst_port == myZ){
        return i;
    }
  }
  return 0;
}

int n3d_add(struct in_addr ip, int src_port, int dst_port){
  int returnId;
	x=(int *)realloc (x, (count+1) * sizeof(int));
	y=(int *)realloc (y, (count+1) * sizeof(int));
	z=(int *)realloc (z, (count+1) * sizeof(int));
	
	if (ifPresent(ntohl(ip.s_addr)-127,src_port-32768,dst_port-32768) == 0){
		x[count]=ntohl(ip.s_addr)-127;
		y[count]=src_port-32768;
		z[count]=dst_port-32768;
		count++;
	}
  if ((returnId=ifPresentMyData(ntohl(ip.s_addr)-127,src_port-32768,dst_port-32768)) == 0){

    myData = (struct net3D*)realloc (myData, (count+1) * sizeof(net3D));

    myData[count].dec_ipv4 = ntohl(ip.s_addr)-127;
    myData[count].src_port = src_port-32768;
    myData[count].dst_port = dst_port-32768;
    myData[count].nb=1;
  } else {
    myData[returnId].nb++;
  }
	return 0;
}
